package handlers

import (
	"log"
	"net/http"
	"strconv"
	"time"

	"excel/database"

	"github.com/gin-gonic/gin"
)

// StatResponse 统计响应结构
type StatResponse struct {
	Username string `json:"username"`
	Count    int    `json:"count"`
}

// UserStatistics 用户统计数据结构
type UserStatistics struct {
	TotalTasks    int            `json:"totalTasks"`
	MonthlyTasks  int            `json:"monthlyTasks"`
	PriorityStats map[string]int `json:"priorityStats"`
	NatureStats   map[string]int `json:"natureStats"`
	SourceStats   map[string]int `json:"sourceStats"`
}

// HandleGetStatistics 处理获取统计数据的请求
func HandleGetStatistics(c *gin.Context) {
	username := c.GetHeader("X-Username")
	roleStr := c.GetHeader("X-Role")
	if username == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
		return
	}

	role, err := strconv.Atoi(roleStr)
	if err != nil || role < 10 {
		// 普通用户只能查看自己的统计数据
		var userStats []StatResponse
		err = database.DB.Select(&userStats, `
            SELECT username, COUNT(*) as count 
            FROM edata 
            WHERE username = ?
            GROUP BY username`,
			username)
		if err != nil {
			log.Printf("Failed to get user statistics: %v", err)
			c.JSON(http.StatusInternalServerError, gin.H{"error": "获取统计数据失败"})
			return
		}
		// 确保返回数组不为空
		if len(userStats) == 0 {
			userStats = append(userStats, StatResponse{
				Username: username,
				Count:    0,
			})
		}
		c.JSON(http.StatusOK, gin.H{
			"userStats": userStats,
		})
		return
	}

	// 管理员可以查看所有用户的统计数据
	var userStats []StatResponse
	err = database.DB.Select(&userStats, `
        SELECT username, COUNT(*) as count 
        FROM edata 
        GROUP BY username 
        ORDER BY count DESC
    `)
	if err != nil {
		log.Printf("Failed to get user statistics: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取统计数据失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"userStats": userStats,
	})
}

// HandleGetUserStatistics 处理获取单个用户的统计数据
func HandleGetUserStatistics(c *gin.Context) {
	username := c.GetHeader("X-Username")
	roleStr := c.GetHeader("X-Role")
	if username == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
		return
	}

	role, err := strconv.Atoi(roleStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的角色信息"})
		return
	}

	targetUser := c.Query("username")

	// 普通用户只能查看自己的统计数据
	if role < 10 && targetUser != "" && targetUser != username {
		c.JSON(http.StatusForbidden, gin.H{"error": "只能查看自己的统计数据"})
		return
	}

	// 如果是普通用户且未指定用户名，则使用当前用户
	if role < 10 {
		targetUser = username
	}

	stats := UserStatistics{
		PriorityStats: make(map[string]int),
		NatureStats:   make(map[string]int),
		SourceStats:   make(map[string]int),
	}

	// 获取总任务数
	err = database.DB.Get(&stats.TotalTasks,
		"SELECT COUNT(*) FROM edata WHERE username = ?",
		targetUser)
	if err != nil {
		log.Printf("Failed to get total tasks: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取统计数据失败"})
		return
	}

	// 获取本月任务数
	currentMonth := time.Now().Format("2006-01")
	monthQuery := "SELECT COUNT(*) FROM edata WHERE DATE_FORMAT(created_at, '%Y-%m') = ? AND username = ?"
	monthParams := []interface{}{currentMonth, targetUser}
	err = database.DB.Get(&stats.MonthlyTasks, monthQuery, monthParams...)
	if err != nil {
		log.Printf("Failed to get monthly tasks: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取统计数据失败"})
		return
	}

	// 获取任务等级分布
	var priorityStats []struct {
		Priority string `db:"task_priority"`
		Count    int    `db:"count"`
	}
	err = database.DB.Select(&priorityStats,
		"SELECT task_priority, COUNT(*) as count FROM edata WHERE username = ? GROUP BY task_priority",
		targetUser)
	if err != nil {
		log.Printf("Failed to get priority stats: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取统计数据失败"})
		return
	}
	for _, stat := range priorityStats {
		stats.PriorityStats[stat.Priority] = stat.Count
	}

	// 获取任务性质分布
	var natureStats []struct {
		Nature string `db:"task_nature"`
		Count  int    `db:"count"`
	}
	err = database.DB.Select(&natureStats,
		"SELECT task_nature, COUNT(*) as count FROM edata WHERE username = ? GROUP BY task_nature",
		targetUser)
	if err != nil {
		log.Printf("Failed to get nature stats: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取统计数据失败"})
		return
	}
	for _, stat := range natureStats {
		stats.NatureStats[stat.Nature] = stat.Count
	}

	// 获取任务来源分布
	var sourceStats []struct {
		Source string `db:"task_source"`
		Count  int    `db:"count"`
	}
	err = database.DB.Select(&sourceStats,
		"SELECT task_source, COUNT(*) as count FROM edata WHERE username = ? GROUP BY task_source",
		targetUser)
	if err != nil {
		log.Printf("Failed to get source stats: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取统计数据失败"})
		return
	}
	for _, stat := range sourceStats {
		stats.SourceStats[stat.Source] = stat.Count
	}

	c.JSON(http.StatusOK, stats)
}
